# encoding=utf-8
import json
import os
import time
import matplotlib
from matplotlib import pyplot as plt
from seg_system import ApplicationConfig

matplotlib.use('Agg')


class TimeRecorder:
    """效率统计工具类
        1. 实现一个注解
            - 输入标识字符，自动统计函数执行时间
        2. matplotlib转换成图像
        3. 文本形式保存
    """
    time_dict = {}

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_inst'):
            cls._inst = super(TimeRecorder, cls).__new__(cls, *args, **kwargs)
        return cls._inst

    @staticmethod
    def time_record():
        def wrapper(func):
            def f(*args, **kwargs):
                start = time.perf_counter()
                r = func(*args, **kwargs)
                end = time.perf_counter()
                cost = end - start

                f_id = func.__name__
                if f_id in TimeRecorder.time_dict:
                    TimeRecorder.time_dict[f_id].append(cost)
                else:
                    TimeRecorder.time_dict[f_id] = [cost]
                return r
            return f
        return wrapper

    def make_path(self, name, path):
        if path:
            path = os.path.join(path, name)
        else:
            path = os.path.join(ApplicationConfig.PathConfig.SYSTEM_RESOURCE, name)
        return path

    def save_img(self, mode: str = 'linear', name: str = 'time_cost.png', path: str = None, **kwargs):
        path = self.make_path(name, path)

        if mode == 'linear':
            plt.figure(figsize=(20, 8), dpi=80)
            plt.title('time cost')
            for each_id in TimeRecorder.time_dict:
                each_list = TimeRecorder.time_dict[each_id]
                plt.plot(range(len(each_list)), each_list,
                         label=each_id)

            plt.grid()
            plt.xlabel('processed number')
            plt.ylabel('each time cost')
            plt.legend(loc='upper right')
            plt.savefig(path)
            plt.cla()
            plt.close()

    def save_txt(self, name: str = 'time_cost.txt', path: str = None, **kwargs):
        path = self.make_path(name, path)

        with open(path, 'w') as f:
            f.write(json.dumps(TimeRecorder.time_dict))
